package com.wuzhun.wxmp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.wuzhun.wxmp.mapper.OperateLogMapper;
import com.wuzhun.wxmp.model.dto.OperateLogDTO;
import com.wuzhun.wxmp.model.entity.OperateLog;
import com.wuzhun.wxmp.service.IOperateLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuzhun.wxmp.util.DateTimeUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 操作日志表 服务实现类
 * </p>
 *
 * @author Paulin
 * @since 2023-06-13
 */
@Service
public class OperateLogServiceImpl extends ServiceImpl<OperateLogMapper, OperateLog> implements IOperateLogService {
    @Resource
    private OperateLogMapper operateLogMapper;

    @Override
    public Page<OperateLogDTO> listByPage(Page<OperateLog> operateLogPage, QueryWrapper<OperateLog> queryWrapper) {
        Page<OperateLog> page = operateLogMapper.selectPage(operateLogPage, queryWrapper);
        return covertPageOperateLog(page);
    }

    private Page<OperateLogDTO> covertPageOperateLog(Page<OperateLog> operateLogPage) {

        Page<OperateLogDTO> pageMessageDTO = new Page<>();
        if (operateLogPage == null || CollectionUtils.isEmpty(operateLogPage.getRecords())) {
            return pageMessageDTO;
        }
        pageMessageDTO.setCurrent(operateLogPage.getCurrent());
        pageMessageDTO.setTotal(operateLogPage.getTotal());
        pageMessageDTO.setPages(operateLogPage.getPages());
        pageMessageDTO.setSize(operateLogPage.getSize());
        List<OperateLog> operateLogList = operateLogPage.getRecords();
        List<OperateLogDTO> operateLogDTOS = Lists.newArrayListWithCapacity(operateLogList.size());
        operateLogList.forEach(operateLog -> operateLogDTOS.add(convertOperateLog(operateLog)));
        pageMessageDTO.setRecords(operateLogDTOS);
        return pageMessageDTO;
    }

    private OperateLogDTO convertOperateLog(OperateLog operateLog) {
        OperateLogDTO dto = new OperateLogDTO();
        BeanUtils.copyProperties(operateLog, dto);
        if (StringUtils.isNotEmpty(operateLog.getParams())) {
            dto.setParamsDesc(operateLog.getParams().substring(0, Math.min(operateLog.getParams().length(), 64)));
        }
        dto.setFormatCreatedTime(DateTimeUtil.getFormatDateTime(operateLog.getCreatedTime()));
        return dto;
    }
}
